package com.example.demo.io.obj;

import org.junit.Test;

import java.io.*;

/**
 * @Author: liull
 * @Description: 序列化/反序列化
 * @Date: Created in 12:31 2020/3/27
 * @Modified By:
 */
public class ObjectIOputStream {

    /**
     * String对象写入文件
     *
     * @throws IOException
     */
    @Test
    public void test1() throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("1.dat"));
        oos.writeObject(new String("没有活就是呆着"));
        oos.close();
    }

    /**
     * 从文件读取String对象 并输出
     *
     * @throws IOException
     * @throws ClassNotFoundException
     */
    @Test
    public void test2() throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("1.dat"));
        Object object = ois.readObject();
        if (object instanceof String) {
            System.out.println(object.toString());
        }
    }

    /**
     * 自定义对象实现序列化 序列化至硬盘（此处为项目路径下）
     */
    @Test
    public void test3() throws IOException {
        Person p = new Person(24, "李端也", true);
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("3.dat"));
        oos.writeObject(p);
        oos.close();
    }

    /**
     * 从文件读取String对象 并输出
     *
     * @throws IOException
     * @throws ClassNotFoundException
     */
    @Test
    public void test4() throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("3.dat"));
        Object object = ois.readObject();
        if (object instanceof Person) {
            System.out.println(object.toString());
        }
    }

}
